package com.utooo.service.purchase;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utooo.dao.purchase.OrderReceiptDetailMapper;
import com.utooo.dao.purchase.OrderReceiptMapper;
import com.utooo.dao.purchase.PurchaseOrderMapper;
import com.utooo.dao.supplier.SupplierDeliveryMaterialMapper;
import com.utooo.dao.supplier.SupplierDeliveryPlanMapper;
import com.utooo.dao.supplier.SupplierOrderDeliveryRecordMapper;
import com.utooo.pojo.domain.purchase.order.OrderReceiptDO;
import com.utooo.pojo.domain.purchase.order.OrderReceiptDetailDO;
import com.utooo.pojo.domain.purchase.order.PurchaseOrderDO;
import com.utooo.pojo.domain.supplier.execute.SupplierDeliveryMaterialDO;
import com.utooo.pojo.domain.supplier.execute.SupplierDeliveryPlanDO;
import com.utooo.pojo.domain.supplier.execute.SupplierOrderDeliveryRecordDO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.utooo.constant.Constans.IGNORED_PROPERTIES;

@Service
@Slf4j
public class OrderReceiptServiceImpl extends ServiceImpl<OrderReceiptMapper, OrderReceiptDO>
        implements OrderReceiptService {


    @Resource
    private PurchaseOrderMapper purchaseOrderMapper;
    @Resource
    private SupplierOrderDeliveryRecordMapper supplierOrderDeliveryRecordMapper;
    @Resource
    private SupplierDeliveryMaterialMapper supplierDeliveryMaterialMapper;
    @Resource
    private OrderReceiptDetailMapper orderReceiptDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrderReceipt(String shipmentId) {
        // 采购订单发货
        LambdaQueryWrapper<SupplierDeliveryMaterialDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SupplierDeliveryMaterialDO::getForeignId, shipmentId);
        List<SupplierDeliveryMaterialDO> supplierDeliveryMaterials =
                supplierDeliveryMaterialMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(supplierDeliveryMaterials)) {
            log.error("采购订单发货物料信息不存在: {}", shipmentId);
            return;
        }

        SupplierOrderDeliveryRecordDO deliveryRecord = supplierOrderDeliveryRecordMapper.selectById(shipmentId);
        if (deliveryRecord == null) {
            log.error("采购订单发货记录不存在: {}", shipmentId);
            return;
        }
        String orderNo = supplierDeliveryMaterials.get(0).getOrderNo();
        OrderReceiptDO orderReceiptDO = new OrderReceiptDO();
        BeanUtil.copyProperties(deliveryRecord, orderReceiptDO, IGNORED_PROPERTIES);
        orderReceiptDO.setReceiptNo(generateReceiptNo());
        orderReceiptDO.setOrderNo(orderNo);
        // 发货单号
        orderReceiptDO.setShipmentNo(shipmentId);
        // 初始化状态是待收货
        orderReceiptDO.setStatus("1");
        Integer totalShipmentQuantity = deliveryRecord.getTotalShipmentQuantity();
        orderReceiptDO.setShipmentQuantity(totalShipmentQuantity);
        orderReceiptDO.setReceivedTotalQuantity(totalShipmentQuantity);
        LambdaQueryWrapper<PurchaseOrderDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseOrderDO::getId, orderNo);
        PurchaseOrderDO purchaseOrder = purchaseOrderMapper.selectOne(wrapper);
        if (purchaseOrder != null) {
            orderReceiptDO.setSupplierCode(purchaseOrder.getSupplierCode());
            orderReceiptDO.setSupplierName(purchaseOrder.getSupplierName());
            orderReceiptDO.setContactPerson(purchaseOrder.getContact());
            orderReceiptDO.setContactPhone(purchaseOrder.getContactPhone());
        }

        this.save(orderReceiptDO);
        // 收货明细信息
        supplierDeliveryMaterials.forEach(i -> {
            OrderReceiptDetailDO orderReceiptDetail = new OrderReceiptDetailDO();
            BeanUtil.copyProperties(i, orderReceiptDetail, IGNORED_PROPERTIES);
            orderReceiptDetail.setOrderNo(orderNo);
            orderReceiptDetail.setShipmentNo(shipmentId);
            orderReceiptDetail.setCategoryCode(i.getMaterialCode());
            orderReceiptDetail.setUnitCode(i.getUnitName());
            orderReceiptDetail.setTaxRateCode(i.getTaxRate());
            orderReceiptDetail.setForeignId(orderReceiptDO.getId());
            orderReceiptDetailMapper.insert(orderReceiptDetail);
        });
    }

    private String generateReceiptNo() {
        String prefix = "GR";
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 查询当天已有的最大订单号
        LambdaQueryWrapper<OrderReceiptDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(OrderReceiptDO::getReceiptNo, prefix + datePart);
        queryWrapper.orderByDesc(OrderReceiptDO::getReceiptNo);
        queryWrapper.last("LIMIT 1");
        OrderReceiptDO orderReceiptDO = this.getOne(queryWrapper);

        // 生成序列号
        int maxSequence = 0;
        if (orderReceiptDO != null) {
            String receiptNo = orderReceiptDO.getReceiptNo();
            maxSequence = Integer.parseInt(receiptNo.substring((prefix + datePart).length()));
        }
        int nextSequence = maxSequence + 1;
        String sequencePart = String.format("%03d", nextSequence);
        return prefix + datePart + sequencePart;
    }
}